<!--
 * @Author: 王坤
 * @LastEditors: Please set LastEditors
 * @Description: 卡账号
-->
<template>
  <div class="lc-input-identity-card">
    <el-input
      v-model="innerValue"
      :minLength="minLength"
      :maxLength="maxLength"
      :clearable="clearable"
      :placeholder="placeholder"
      v-bind="$attrs"
      @input="handleInput"
      @blur="handleBlur"
    ></el-input>
    <div class="lc-validate-icon" v-show="validateMark === -1">
      {{ errorNotice }}
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  clearable: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: ''
  },
  errorNotice: {
    type: String,
    default: '身份证号格式错误'
  }
});
const emits = defineEmits(['update:modelValue']);
const innerValue = ref(props.modelValue);
// 0未校验 1格式正确 -1格式错误
const validateMark = ref(0);
const minLength = 15;
const maxLength = 18;
const regIdentityCard18 =
  /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
const regIdentityCard15 =
  /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/;
function handleInput(val) {
  validateMark.value = 0;
  const lastChar = val?.slice(val.length - 1);
  if (isNaN(lastChar) && lastChar !== 'X') {
    innerValue.value = innerValue.value.slice(0, -1);
  }
  emits('update:modelValue', innerValue.value);
}
function handleBlur() {
  const val = innerValue.value;
  if (new RegExp(regIdentityCard18).test(val) || new RegExp(regIdentityCard15).test(val)) {
    validateMark.value = 1;
  } else {
    validateMark.value = -1;
  }
}
</script>
<style lang="scss">
@use '@/assets/styles/variables.scss';
@use '@/assets/styles/mixin.scss';
.lc-input-identity-card {
  @include mixin.createCssFromStyles('& .el-input__wrapper');
  @include mixin.createCssByAttributeMaps('& .el-input__inner', variables.$common-style-maps);
  & {
    display: inline-block;
    position: relative;
  }
  .lc-validate-icon {
    position: absolute;
    top: 100%;
    left: 0;
    padding-top: 4px;
    color: var(--error-color);
    font-size: 12px;
    line-height: 1;
  }
}
</style>
